<?php
    class Util
    {
        /**
         * Checks MX record corresponding to host name in
         * given email address
         *
         * @param string $email Valid email address
         */
        public static function CheckMXRecord($email)
        {
            $matches = explode('@', $email);
            if (!isset($matches[1]))
            {
                return false;
            }

            $host = $matches[1];

            exec('nslookup -type=MX ' . escapeshellarg($host), $result);
            if (!empty($result))
            {
                foreach ($result as $line)
                {
                    if (preg_match("/^$host(.*)mail exchanger = .*/", $line))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

        /**
         * Checks email validity
         *
         * @param string $email
         * @return bool
         */
        public static function IsValidEmail($email)
        {
            $isEmptyEmail = !isset($email) || empty($email);
            if ($isEmptyEmail)
            {
                return false;
            }

            $email = filter_var($email, FILTER_VALIDATE_EMAIL);
            if ($email === false)
            {
                return false;
            }

            if (!self::checkMXRecord($email))
            {
                return false;
            }

            return true;
        }
    }